<template>
  <div class="department-container">
    <!-- 顶部操作栏 -->
    <div class="top-bar">
      <div class="title-section">
        <i class="el-icon-office-building"></i>
        <span>部门管理</span>
      </div>
    </div>

    <!-- 部门树形结构 -->
    <div class="department-tree">
      <el-tree
        v-loading="loading"
        :data="departmentData"
        :props="defaultProps"
        node-key="id"
        default-expand-all
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <div class="node-content">
            <span class="department-name">
              <i class="el-icon-folder-opened"></i>
              <span class="dept-info">
                {{ data.name }}
                <span class="dept-code" v-if="data.code">({{ data.code }})</span>
              </span>
            </span>
            <div class="operation-group">
              <el-tooltip content="查看详情" placement="top">
                <el-button type="text" icon="el-icon-view" @click.stop="handleDetail(data)">
                </el-button>
              </el-tooltip>
              <el-tooltip content="修改部门" placement="top">
                <el-button type="text" icon="el-icon-edit" @click.stop="handleEdit(data)">
                </el-button>
              </el-tooltip>
              <el-tooltip content="添加子部门" placement="top">
                <el-button type="text" icon="el-icon-plus" @click.stop="handleAdd(data)">
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除部门" placement="top">
                <el-button 
                  type="text" 
                  icon="el-icon-delete" 
                  class="delete-btn"
                  @click.stop="handleDelete(data)">
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </span>
      </el-tree>
    </div>

    <!-- 部门详情对话框 -->
    <el-dialog
      title="部门详情"
      :visible.sync="detailDialogVisible"
      width="500px"
      custom-class="department-dialog"
      :modal="true"
      :modal-append-to-body="false"
      :append-to-body="true"
      :close-on-click-modal="true"
    >
      <el-form
        label-width="100px"
      >
        <el-form-item label="部门名称">
          <el-input v-model="currentDept.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="部门编码">
          <el-input v-model="currentDept.code" disabled></el-input>
        </el-form-item>
        <el-form-item label="部门编号">
          <el-input v-model="currentDept.title" disabled></el-input>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-input v-model="currentDept.parentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="部门职责">
          <el-input
            type="textarea"
            v-model="currentDept.duties"
            :rows="3"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="部门描述">
          <el-input
            type="textarea"
            v-model="currentDept.description"
            :rows="3"
            disabled
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 修改部门对话框 -->
    <el-dialog
      :title="editForm.id ? '修改部门' : '添加部门'"
      :visible.sync="editDialogVisible"
      width="500px"
      custom-class="department-dialog"
      :close-on-click-modal="true"
      :modal-append-to-body="false"
      :append-to-body="true"
      :destroy-on-close="true"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="editForm.code" placeholder="请输入部门编码"></el-input>
        </el-form-item>
        <el-form-item label="部门编号" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入部门编号"></el-input>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-input v-model="editForm.parentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="部门职责" prop="duties">
          <el-input
            type="textarea"
            v-model="editForm.duties"
            :rows="3"
            placeholder="请输入部门职责"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input
            type="textarea"
            v-model="editForm.description"
            :rows="3"
            placeholder="请输入部门描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="submitLoading">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'OrgDepartments',
  data() {
    return {
      loading: false,
      departmentData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      detailDialogVisible: false,
      currentDept: {},
      editDialogVisible: false,
      editForm: {
        id: '',
        name: '',
        code: '',
        title: '',
        parentId: '',
        duties: '',
        description: '',
        level: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入部门编号', trigger: 'blur' }
        ]
      },
      submitLoading: false
    }
  },
  created() {
    this.fetchDepartmentData()
  },
  methods: {
    async fetchDepartmentData() {
      try {
        this.loading = true;
        const res = await this.$axios.get('/employee/department')
        console.log(res);
        
        if (res && res.result === 200) {
          // 后端返回的数据结构中，数据在 data 字段中
          this.departmentData = res.data || []
          console.log('部门数据：', this.departmentData)
        } else {
          this.$message.error( '获取部门数据失败')
        }
      } catch (error) {
        console.error('获取部门数据出错：', error)
        this.$message.error('获取部门数据失败')
      } finally {
        this.loading = false
      }
    },

    handleDetail(data) {
      this.currentDept = data
      this.detailDialogVisible = true
    },
    handleEdit(data) {
      this.editForm = {
        id: data.id,
        name: data.name,
        code: data.code,
        title: data.title,
        parentId: data.parentId || '',
        duties: data.duties || '',
        description: data.description || '',
        level: data.level 
      }
      this.editDialogVisible = true
    },
    handleAdd(data) {
      this.editForm = {
        id: '',
        name: '',
        code: '',
        title: '',
        parentId: data.code,
        duties: '',
        description: '',
        level: data.level + 1
      }
      this.editDialogVisible = true
    },
    handleDelete(data) {
      this.$confirm('确认删除该部门吗？此操作不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await this.$axios.delete('/employee/department', {
            params: { id: data.id }
          })
          
          if (response && response.result === 200) {
            this.$message.success('删除成功')
            // 重新获取部门数据
            await this.fetchDepartmentData()
          } else {
            this.$message.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除部门出错：', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        // 取消删除，不做任何操作
      })
    },
    async submitEdit() {
      try {
        await this.$refs.editForm.validate()
        
        this.submitLoading = true
        const response = await this.$axios.post('/employee/department', this.editForm)
        
        if (response && response.result === 200) {
          this.$message.success(this.editForm.id ? '修改成功' : '添加成功')
          this.editDialogVisible = false
          // 重新获取部门数据
          await this.fetchDepartmentData()
        } else {
          this.$message.error(response.message || (this.editForm.id ? '修改失败' : '添加失败'))
        }
      } catch (error) {
        console.error('操作失败：', error)
        this.$message.error(this.editForm.id ? '修改失败' : '添加失败')
      } finally {
        this.submitLoading = false
      }
    }
  }
}
</script>

<style scoped>
.department-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  min-height: calc(100vh - 120px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  display: flex;
  align-items: center;
  font-size: 18px;
  /* font-weight: 600; */
  color: #303133;
}

.title-section i {
  margin-right: 8px;
  font-size: 20px;
  color: #409EFF;
}

.department-tree {
  padding: 10px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
}

.node-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 32px;
}

.department-name {
  display: flex;
  align-items: center;
}

.department-name i {
  margin-right: 5px;
  color: #909399;
}

.operation-group {
  display: none;
  align-items: center;
}

.node-content:hover .operation-group {
  display: flex;
}

.operation-group .el-button {
  margin-left: 8px;
  font-size: 16px;
  padding: 0 8px;
}

.operation-group .el-button:hover {
  color: #409EFF;
}

.operation-group .delete-btn:hover {
  color: #F56C6C;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree-node:focus > .el-tree-node__content) {
  background-color: #ecf5ff;
}

.dept-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dept-code {
  color: #909399;
  font-size: 12px;
}

/* 对话框样式优化 */
:deep(.department-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.department-dialog .el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fff;
}

:deep(.department-dialog .el-dialog__body) {
  padding: 0;
  background-color: #fff;
}

:deep(.department-dialog .el-dialog__headerbtn) {
  top: 20px;
}

:deep(.el-dialog__wrapper) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.v-modal) {
  opacity: 0.5;
  background: #000;
}

.detail-content {
  padding: 20px;
  background-color: #fff;
}

.detail-item {
  margin-bottom: 16px;
  line-height: 1.5;
  display: flex;
}

.detail-item .label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
  width: 80px;
  flex-shrink: 0;
}

.detail-item span:last-child {
  color: #303133;
  flex: 1;
}

.dialog-footer {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-textarea__inner) {
  border-radius: 4px;
}

:deep(.el-dialog__wrapper) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.department-dialog) {
  margin: 0 !important;
}

:deep(.v-modal) {
  opacity: 0.5;
  background: #000;
}
</style> 